package com.dataseek.iot.toolkit.auth.component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dataseek.iot.toolkit.auth.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class MetaHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        try {
            LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String name = principal.getSysUser().getUserName();
            this.setFieldValByName("createBy", name, metaObject);
            this.setFieldValByName("updateBy", name, metaObject);
        } catch (Exception e) {
            log.error("createBy/updateBy插入失败，Exception:" + e);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        try {
            LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String name = principal.getSysUser().getUserName();
            this.setFieldValByName("updateBy", name, metaObject);
        } catch (Exception e) {
            log.error("createBy/updateBy插入失败，Exception:" + e);
        }
    }
}
